package com.lyl.quartz.test;

import com.lyl.quartz.jobs.HelloJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.concurrent.TimeUnit;

/**
 * 多个trigger调用一个job
 * @author lylbell
 * @date 2022-03-29 10:35
 */
public class _02_QuartzTest_MultTrigger {

    public static void main(String[] args) throws SchedulerException, InterruptedException {

        // 调度器工厂创建默认调度器
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        // 启动调度器
        scheduler.start();

        // 创建job
        JobDetail job = JobBuilder.newJob(HelloJob.class).withIdentity("job1", "group1").build();

        // 创建trigger。withIntervalInSeconds：每5秒执行一次。
        // repeatForever：一直重复执行
        // 执行5次。0 1 2 3
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "group1")
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).repeatForever()).build();


        // forJob:指定job
        // 0 3
        Trigger trigger2 = TriggerBuilder.newTrigger()
                .withIdentity("trigger2", "group1")
                .forJob("job1","group1")
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3).repeatForever()).build();



        scheduler.scheduleJob(job,trigger);

        // 调度trigger2。如果没有初始化job1的话，就必须在此处指定job1
        // 未初始化：报错The job (group1.job1) referenced by the trigger does not exist.
        // 同时写多个 scheduler.scheduleJob(job,trigger2);多trigger引用一个job，会报错：Unable to store Job : 'group1.job1', because one already exists with this identification.
        scheduler.scheduleJob(trigger2);


        // 执行3秒
        TimeUnit.SECONDS.sleep(3);

        scheduler.shutdown();
    }
}
